package world.xuewei.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import world.xuewei.dao.CommodityDao;
import world.xuewei.dao.OrderItemDao;
import world.xuewei.dao.OrdersDao;
import world.xuewei.model.entity.Commodity;
import world.xuewei.model.entity.OrderItem;
import world.xuewei.model.entity.Orders;
import world.xuewei.model.entity.R;
import world.xuewei.service.OrdersService;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单主表(Orders)表控制层
 *
 * @author makejava
 * @since 2024-11-16 15:40:06
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Resource
    private OrdersService orderService;

    @Resource
    private CommodityDao commodityDao;

    @Resource
    private OrdersDao ordersDao;


    @PostMapping("/create")
    public R createOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            // 1. 获取参数
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);
            Long merchantId = Long.parseLong(params.get("merchantId").toString());

            Integer deliveryType = Integer.parseInt(params.get("deliveryType").toString());

            String remark = params.get("remark").toString();
            if (StringUtils.hasText(remark)) {
                int length = remark.replaceAll("[^\\x00-\\xff]", "**").length();
                if (length > 100) {
                    return R.error().message("备注不能超过100个英文字符或50个汉字");
                }
            }
            // 如果是外送，则需要地址ID
            Long addressId = null;
            if (deliveryType == 0) {
                addressId = Long.parseLong(params.get("addressId").toString());
            }

            List<Map<String, Object>> itemsMap = (List<Map<String, Object>>) params.get("items");
            if (itemsMap == null || itemsMap.isEmpty()) {
                return R.error().message("订单商品不能为空");
            }

            // 2. 检查商品库存
            List<OrderItem> items = new ArrayList<>();
            // 用于验证所有商品是否属于同一商户
            for (Map<String, Object> item : itemsMap) {
                // 商品ID
                Long commodityId = Long.parseLong(item.get("commodityId").toString());
                // 购买数量
                Integer quantity = Integer.parseInt(item.get("quantity").toString());

                // 查询商品信息
                Commodity commodity = commodityDao.queryById(commodityId);
                if (commodity == null) {
                    return R.error().message("商品不存在: " + commodityId);
                }

                // 验证商品状态
                if (commodity.getStatus() != 1) {
                    return R.error().message("商品已下架: " + commodity.getName());
                }

                // 验证商户
                if (merchantId == null) {
                    merchantId = commodity.getMerchantId();
                } else if (!merchantId.equals(commodity.getMerchantId())) {
                    return R.error().message("不能在同一订单中购买不同商户的商品");
                }

                // 验证库存
                if (commodity.getInventory() < quantity) {
                    return R.error().message("商品 " + commodity.getName() + " 库存不足");
                }


                // 构建订单项
                OrderItem orderItem = new OrderItem();
                orderItem.setCommodityId(commodityId);
                orderItem.setQuantity(quantity);
                // 设置规格信息
                orderItem.setCupSize((String) item.get("cupSize"));
                orderItem.setSugarLevel((String) item.get("sugarLevel"));
                orderItem.setTemperature((String) item.get("temperature"));
                orderItem.setCoffeeBean((String) item.get("coffeeBean"));
                orderItem.setIntensity((String) item.get("intensity"));
                items.add(orderItem);
            }


            // 3. 创建订单
            String orderNumber = orderService.createOrder(userId,merchantId, addressId, remark,deliveryType, items);
            return R.ok().data("orderNumber", orderNumber);

        } catch (Exception e) {
            log.error("创建订单失败", e);
            return R.error().message("订单创建失败：" + e.getMessage());
        }
    }

    @PostMapping("/createNoToken")
    public R createOrderNoToken(@RequestBody Map<String, Object> params) {
        try {
            // 1. 获取参数
            Long userId = Long.parseLong(params.get("userId").toString());
            Long commodityId = Long.parseLong(params.get("commodityId").toString());
            Integer quantity = Integer.parseInt(params.get("quantity").toString());

            // 2. 查询商品信息
            Commodity commodity = commodityDao.queryById(commodityId);
            if (commodity == null) {
                return R.error().message("商品不存在");
            }

            // 3. 检查商品库存
            if (commodity.getInventory() < quantity) {
                return R.error().message("商品 " + commodity.getName() + " 库存不足");
            }

            // 4. 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setCommodityId(commodityId);
            orderItem.setQuantity(quantity);
            orderItem.setCupSize(params.get("cupSize").toString());
            orderItem.setSugarLevel(params.get("sugarLevel").toString());
            orderItem.setTemperature(params.get("temperature").toString());
            orderItem.setCoffeeBean(params.get("coffeeBean").toString());
            orderItem.setIntensity(params.get("intensity").toString());
            orderItem.setMerchantId(commodity.getMerchantId());

            List<OrderItem> items = new ArrayList<>();
            items.add(orderItem);

            // 5. 创建订单
            String orderNumber = orderService.createOrder(
                    userId,
                    commodity.getMerchantId(),
                    null,  // 自取不需要地址
                    "",    // 无备注
                    1,     // 自取方式
                    items
            );

            return R.ok().data("orderNumber", orderNumber);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return R.error().message("创建订单失败：" + e.getMessage());
        }
    }


    /**
     * 查询订单详情
     * GET /order/detail/{orderNumber}
     */
    @GetMapping("/detail/{orderNumber}")
    public R getOrderDetail(@PathVariable String orderNumber,HttpServletRequest request) {
        try {
            // 1. 获取参数
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);

            Orders order = orderService.getOrderDetail(orderNumber);
            if (order == null) {
                return R.error().message("订单不存在");
            }
            // 判断登入用户有无权限获取信息
            if (!order.getMerchantId().equals(userId) && !order.getUserId().equals(userId)) {
                return R.error().message("该账号无权获取该订单详情");
            }

            return R.ok().data("order", order);
        } catch (Exception e) {
            return R.error().message("查询失败：" + e.getMessage());
        }
    }


    // id查询用户订单信息
    @GetMapping("/userbyid")
    public R getUserOrders(HttpServletRequest request) {
        try {
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);
            List<Orders> orders = orderService.getUserOrders(userId);
            return R.ok().data("orders", orders);
        } catch (Exception e) {
            return R.error().message("获取订单列表失败：" + e.getMessage());
        }
    }

    // id查询商户订单信息
    @GetMapping("/merchantbyid")
    public R getMerchantOrders(HttpServletRequest request) {
        try {
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);
            List<Orders> orders = orderService.getMerchantOrders(userId);
            return R.ok().data("orders", orders);
        } catch (Exception e) {
            return R.error().message("获取商户订单列表失败：" + e.getMessage());
        }
    }



    /**
     * 支付订单
     * POST /order/pay/{orderNumber}
     */
    @PostMapping("/pay/{orderNumber}")
    public R payOrder(@PathVariable String orderNumber) {
        try {
            orderService.payOrder(orderNumber);
            return R.ok().message("支付成功");
        } catch (Exception e) {
            return R.error().message("支付失败：" + e.getMessage());
        }
    }


    /**
     * 商家出餐
     * POST /order/prepare/{orderNumber}
     */
    @PostMapping("/prepare/{orderNumber}")
    public R prepareMeal(@PathVariable String orderNumber,HttpServletRequest request) {
        try {
            Orders order = ordersDao.getOrderDetail(orderNumber);
            // 1. 获取参数
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);

            // 判断登入用户有无权限获取信息
            if (!order.getMerchantId().equals(userId)) {
                return R.error().message("该账号无权操作");
            }


            orderService.prepareMeal(orderNumber);
            return R.ok().message("出餐成功");
        } catch (Exception e) {
            return R.error().message("出餐失败：" + e.getMessage());
        }
    }

    /**
     * 确认取餐
     * POST /order/pickup/{orderNumber}
     */
    @PostMapping("/pickup/{orderNumber}")
    public R confirmPickup(@PathVariable String orderNumber,HttpServletRequest request) {
        try {
            // 1. 获取参数
            String userIdStr = (String) request.getAttribute("userId");
            Long userId = Long.parseLong(userIdStr);

            Orders order = ordersDao.getOrderDetail(orderNumber);
            // 判断登入用户有无权限获取信息
            if (!order.getMerchantId().equals(userId)) {
                return R.error().message("该账号无权操作");
            }

            orderService.confirmPickup(orderNumber);
            return R.ok().message("取餐成功");
        } catch (Exception e) {
            return R.error().message("取餐失败：" + e.getMessage());
        }
    }


    // 取消订单
    @PostMapping("/cancel/{orderNumber}")
    public R cancelOrder(@PathVariable String orderNumber) {
        try {
            orderService.cancelOrder(orderNumber);
            return R.ok().message("订单取消成功");
        } catch (Exception e) {
            return R.error().message("订单取消失败：" + e.getMessage());
        }
    }


}

